<?php

declare(strict_types=1);

namespace App\Controller\Webhook;

use App\Repository\WebhookRepository;
use Psr\Http\Message\ResponseFactoryInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Yiisoft\Http\Header;
use Yiisoft\Http\Status;
use Yiisoft\Router\UrlGeneratorInterface;

use function is_array;
use function is_string;
use function trim;

final readonly class CreateAction
{
    public function __construct(
        private WebhookRepository $webhooks,
        private ResponseFactoryInterface $responseFactory,
        private UrlGeneratorInterface $urlGenerator,
    ) {}

    public function __invoke(ServerRequestInterface $request): ResponseInterface
    {
        $label = $this->extractLabel($request->getParsedBody());
        $webhook = $this->webhooks->create($label);

        $response = $this->responseFactory->createResponse(Status::SEE_OTHER);

        return $response->withHeader(
            Header::LOCATION,
            $this->urlGenerator->generate('webhook.show', ['token' => $webhook['token']]),
        );
    }

    private function extractLabel(mixed $parsedBody): ?string
    {
        if (!is_array($parsedBody)) {
            return null;
        }

        $value = $parsedBody['label'] ?? null;

        if (!is_string($value)) {
            return null;
        }

        $value = trim($value);

        return $value === '' ? null : $value;
    }
}
